
<template>

  <div>
    <el-card >
      <div>
        <div class="flex-input">
          <div>
            <el-input  v-model="getListParme.cwPznm"   placeholder="凭证内码" />
          </div>
          <div>
            <el-input  v-model="getListParme.projectName"   placeholder="项目名称" />
          </div>
          <div>
            <el-input v-model="getListParme.chargerName"  placeholder="负责人" />
          </div>

          <div style="min-width: 266px">
            <el-button icon="ArrowLeft"  @click="searchOpen = !searchOpen">更多</el-button>
            <el-button type="primary" icon="Search" @click="confirmClick">查询</el-button>
            <el-button  icon="Search" @click="reset">重置</el-button>
          </div>
        </div>


        <div class="flex-input" v-show="searchOpen">
          <div>
            <el-input  v-model="getListParme.note"   placeholder="摘要" />
          </div>
          <div>
            <el-select
                v-model="getListParme.unitId"
                multiple
                collapse-tags
                filterable
                collapse-tags-tooltip
                placeholder="所属单位"
                @focus="getsuoshudanweiOptions"
            >
              <el-option
                  v-for="item in suoshudanweiOptions"
                  :key="item.codeColumn"
                  :label="item.valueColumn"
                  :value="item.codeColumn"
              />
            </el-select>
          </div>
          <div>
            <el-select
                v-model="getListParme.projectType"
                multiple
                collapse-tags
                filterable
                collapse-tags-tooltip
                placeholder="项目分类"
                @focus="getxiangmufenleiOptions"
            >
              <el-option
                  v-for="item in xiangmufenleiOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </div>
          <div>
            <el-select
                v-model="getListParme.projectClass"
                multiple
                collapse-tags
                filterable
                collapse-tags-tooltip
                placeholder="项目性质"
                @focus="getxiangmuxingzhiOptions"
            >
              <el-option
                  v-for="item in xiangmuxingzhiOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </div>
          <div class="data-flex">
            <div  class="date-picker-wrapper">
              <el-date-picker
                  v-model="valueDate"
                  :type="year"
                  style="width: 100%;"
                  range-separator="至"
                  start-placeholder="支出时间开始时间"
                  end-placeholder="支出时间结束时间"

              />
            </div>
            <div  class="select-wrapper">
              <!--          <el-radio-group v-model="year" aria-label="size control">-->
              <!--            <el-radio-button value="daterange">年/月/日</el-radio-button>-->
              <!--            <el-radio-button value="monthrange">月</el-radio-button>-->
              <!--            <el-radio-button value="yearrange">年</el-radio-button>-->
              <!--          </el-radio-group>-->
              <div class="data-selete">
                <el-select
                    v-model="year"
                    placeholder="请选择"
                    style="width: 100%;"
                    @change="valueDate=[]"
                >
                  <el-option
                      v-for="item in optionsdata"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>

              </div>
            </div>
          </div>
          <div class="aaaaa">
            <div>
              <el-input
                  v-model="getListParme.params.minfee"
                  placeholder="最小支出金额"
                  @input="handleInput('expense','min')"
                  :maxlength="15"
              />
            </div>
            <div class="zhi">至</div>
            <div>
              <el-input
                  v-model="getListParme.params.maxfee"
                  placeholder="最大支出金额"
                  @input="handleInput('expense','max')"
                  :maxlength="15"
              />
            </div>
          </div>
          <div class="aaaaa">
            <div>
              <el-input
                  v-model="getListParme.params.minprofee"
                  placeholder="最小合同金额"
                  @input="handleInput('contract','min')"
                  :maxlength="15"
              />
            </div>
            <div class="zhi">至</div>
            <div>
              <el-input
                  v-model="getListParme.params.maxprofee"
                  placeholder="最大合同金额"
                  @input="handleInput('contract','max')"
                  :maxlength="15"

              />
            </div>
          </div>
        </div>
      </div>

    </el-card>
    <el-card style="margin-top: 10px">
      <jfzcTable ref="getchildListjfzc" v-model="getListParme"></jfzcTable>
    </el-card>

    <DialogComponent ref="dialogRef" @save="handleSave" @saveAndPass="handleSaveAndPass" />
  </div>
</template>

<script setup lang="ts">
import jfzcTable from '@/views/money/jfzc/jfzcTable.vue';
import {onBeforeMount, ref} from "vue";
import DialogComponent from './jfzcDialogCompile.vue';
import {
  getCategory,
  list
} from '@/api/money/jfzcApi'

//处理最大-最小支出和合同
const contractAmountError = ref('');//错误信息合同
const expenseAmountError = ref('');//错误信息支出

// 处理输入的通用函数
const handleInput = (type, inputType) => {
  let minKey, maxKey, errorRef;
  if (type === 'contract') {
    minKey = 'minprofee';
    maxKey = 'maxprofee';
    errorRef = contractAmountError;
  } else if (type === 'expense') {
    minKey = 'minfee';
    maxKey = 'maxfee';
    errorRef = expenseAmountError;
  }

  if (inputType ==='min') {
    getListParme.value.params[minKey] = getListParme.value.params[minKey].replace(/[^\d.]/g, '');
  } else {
    getListParme.value.params[maxKey] = getListParme.value.params[maxKey].replace(/[^\d.]/g, '');
  }

  validateAmount(type, errorRef);
};

// 验证金额输入的通用函数
const validateAmount = (type, errorRef) => {
  let minKey, maxKey;
  if (type === 'contract') {
    minKey = 'minprofee';
    maxKey = 'maxprofee';
  } else if (type === 'expense') {
    minKey = 'minfee';
    maxKey = 'maxfee';
  }

  const min = parseFloat(getListParme.value.params[minKey]);
  const max = parseFloat(getListParme.value.params[maxKey]);

  // 检查最小金额是否小于等于最大金额
  if (getListParme.value.params[minKey]!== '' && getListParme.value.params[maxKey]!== '' && min > max) {
    errorRef.value = `最小${type === 'contract'? '合同' : '支出'}金额不能大于最大${type === 'contract'? '合同' : '支出'}金额`;
    return;
  }

  // 检查金额是否为非负数
  if (min < 0 && getListParme.value.params[minKey]!== '') {
    errorRef.value = `最小${type === 'contract'? '合同' : '支出'}金额不能为负数`;
    return;
  }
  if (max < 0 && getListParme.value.params[maxKey]!== '') {
    errorRef.value = `最大${type === 'contract'? '合同' : '支出'}金额不能为负数`;
    return;
  }

  // 如果没有错误，清除错误信息
  errorRef.value = '';
};
//处理最大-最小支出和合同end
//查询按钮
const getchildListjfzc = ref(null)
// 假设 formatDate 函数定义如下
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
const confirmClick = function (){
  console.log(getListParme.value)
  console.log(valueDate.value)
  if(valueDate.value == null){
    valueDate.value = []
  }
  if (valueDate.value && valueDate.value.length === 2) {
    // 根据选择类型处理日期范围
    if (year.value === 'yearrange') {
      // 按年选择：设置为当年的1月1日至12月31日
      const startYear = valueDate.value[0].getFullYear();
      const endYear = valueDate.value[1].getFullYear();

      const startDate = new Date(startYear, 0, 1); // 1月1日
      const endDate = new Date(endYear, 11, 31);  // 12月31日

      // 更新 valueDate 和查询参数，使用 formatDate 函数格式化日期
      valueDate.value = [startDate, endDate];
      getListParme.value.params.beginTime = formatDate(startDate);
      getListParme.value.params.endTime = formatDate(endDate);
    } else if (year.value === 'monthrange') {
      // 按月选择：设置为当月的第一天至最后一天
      const startMonth = valueDate.value[0];
      const endMonth = valueDate.value[1];

      const startDate = new Date(startMonth.getFullYear(), startMonth.getMonth(), 1);
      const endDate = new Date(endMonth.getFullYear(), endMonth.getMonth() + 1, 0);

      // 更新 valueDate 和查询参数，使用 formatDate 函数格式化日期
      valueDate.value = [startDate, endDate];
      getListParme.value.params.beginTime = formatDate(startDate);
      getListParme.value.params.endTime = formatDate(endDate);
    } else {
      // 按日选择：直接使用选择的值，使用 formatDate 函数格式化日期
      getListParme.value.params.beginTime = formatDate(valueDate.value[0]);
      getListParme.value.params.endTime = formatDate(valueDate.value[1]);
    }
  } else {
    // 未选择有效日期范围，清空查询参数
    getListParme.value.params.beginTime = '';
    getListParme.value.params.endTime = '';
  }


  getchildListjfzc.value.getslist();
}
//重置
const reset = () => {
  for (const key in getListParme.value) {
    if (typeof getListParme.value[key] === 'object' && getListParme.value[key]!== null) {
      // 处理嵌套对象
      for (const subKey in getListParme.value[key]) {
        getListParme.value[key][subKey] = '';
      }
    } else {
      getListParme.value[key] = '';
    }
    // 单独处理 unitId，将其置为空数组
    if (key === 'unitId') {
      getListParme.value[key] = [];
    }
  }
  // 清空 valueDate
  valueDate.value = [];
}
//项目性质
const xiangmuxingzhiOptions = ref([])
const getxiangmuxingzhiOptions = function (){
  getCategory({
    'bizName':'项目性质'
  })
      .then((res)=>{
        xiangmuxingzhiOptions.value = res.data
      })
}

//项目分类
const xiangmufenleiOptions = ref([])
const getxiangmufenleiOptions = function (){
  getCategory({
    'bizName':'项目分类（所有-有级联）'
  })
      .then((res)=>{
        xiangmufenleiOptions.value = res.data
      })
}

//所属单位
const suoshudanweiOptions = ref([])
const getsuoshudanweiOptions = function (){
  getCategory({
    'bizName':'成果归属单位'
  })
      .then((res)=>{
        suoshudanweiOptions.value = res.data
      })
}


const searchOpen = ref(false)

const getListParme = ref ({
  cwPznm:'',//凭证内码
  projectId:'',//项目id
  projectName:'',//项目名称
  chargerName:'', //负责人
  note:'',//摘要
  unitId:[],//所属单位
  projectType:[],//项目分类
  projectClass:[],//项目性质
  orderByColumn:"b.payout_date",
  isAsc:"descending",
  params:{
    minfee:'',//最小支出金额
    maxfee:'',//最大支出金额
    beginTime:'',//支出时间
    endTime:'',//支出时间
    minprofee:'',//最小批合同金额
    maxprofee:'',//最大批合同金额
  },
})



const dialogRef = ref(null);

// 打开弹窗的方法
const openDialog = () => {
  dialogRef.value.openDialog();
};

// 处理子组件保存事件
const handleSave = (data) => {
  console.log('父组件接收到保存数据:', data);
};

// 处理子组件保存并通过事件
const handleSaveAndPass = (data) => {
  console.log('父组件接收到保存并通过数据:', data);
};
//时间区间选择
const optionsdata = [
  {
    value: 'daterange',
    label: '年/月/日',
  },
  {
    value: 'monthrange',
    label: '月',
  },
  {
    value: 'yearrange',
    label: '年',
  },

]

const year = ref<'daterange' | 'monthrange' | 'yearrange'>('daterange')

const valueDate = ref([])
//时间区间选择end
</script>
<style scoped lang="scss">
.title-flex{
  display: flex;
  justify-content: space-between;
  text-align: center;

}
.flex-input{
  display: flex;
  flex-wrap: wrap;
  min-width: 1100px;
}
.flex-input>div{
  width: 24%;
  margin: 10px 10px 0 0;
}
.data-flex {
  display: flex;
  gap: 10px; /* 元素之间的间距 */

}
.aaaaa{
  display: flex;
  flex-grow: 2;

}
.date-picker-wrapper {
  flex: 1; /* 占据剩余空间 */
}
.select-wrapper {
  width: 80px; /* 选择器的固定宽度 */
  min-width: 80px; /* 最小宽度 */
}
.zhi{
line-height: 30px;
}
</style>